<template>
  <div class="container">
    <div>
      <label>Prompt</label>
      <button @click="generatorAudio">生成&播放</button>
      <textarea class="input" v-model=prompt></textarea>
    </div>
    <div class="output">
      <div> >> {{status}}</div>
      <audio ref="audioEl"></audio>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
const prompt = ref('你好，请问有什么能帮到你的吗？')
const status = ref('ready')
const audioEl = ref(null)

const generatorAudio = async () => {
  const token = import.meta.env.VITE_ACCESS_TOKEN
  const appId = import.meta.env.VITE_APP_ID
  const clusterID = import.meta.env.VITE_CLUSTER_ID
  const voiceName = "zh_female_shuangkuaisisi_emo_v2_mars_bigtts"

  const endpoint = '/tts/api/v1/tts'
  const heders = {
    'Authorization': `Bearer; ${token}`,
    'Content-Type': 'application/json',
  }
  const payload = {
    app: {
      appid: appId,
      cluster: clusterID,
      token 
    },
    user: {
      uid: 'bearbobo'
    },
    audio: {
      voice_type: voiceName,
      encoding: 'ogg_opus',
      emotion: 'happy'
    },
    request: {
      reqid: Math.random().toString(36).substring(7),
      text: prompt.value,
      text_type: 'plain',
      operation: 'query',
      silence_duration: '125',
      with_frontend: '1',
      frontend_type: 'unitTson',
      pure_english_opt: '1'
    }
  }

  status.value = 'generating'
  const res = await fetch(endpoint, {
    method: 'POST',
    headers: heders,
    body: JSON.stringify(payload)
  })
  const data = await res.json()
  if (!data.data) {
    throw new Error(data);
  }

  const url = streamToBlob(data.data)
  
  audioEl.value && (audioEl.value.src = url)
  audioEl.value.play()
  status.value = 'done'

}



// 将 base64 的音频流转换为 Blob 对象
const streamToBlob = (stream) => {
  const byteArrays = []
  const byteCharacters = atob(stream)
  for (let offset = 0; offset < byteCharacters.length; offset++) {
    const byteArray = byteCharacters.charCodeAt(offset)
    byteArrays.push(byteArray)
  }
  const blob = new Blob([new Uint8Array(byteArrays)], { type: 'audio/mp3' })
  return URL.createObjectURL(blob)
}

</script>

<style lang="css" scoped>
.input {
  width: 100%;
  height: 2rem;
  font-size: 1rem;
  padding: 0.5rem;
  border: 1px solid #ccc;
  border-radius: 0.5rem;
}

.progress {
  width: 100%;
  height: 0.1rem;
  margin: .4rem 0;
  background: #ccc;
}

.progress>div {
  background: #c00;
  height: 100%;
}

.container {
  display: flex;
  flex-direction: column;
  align-items: start;
  justify-content: start;
  height: 100vh;
}

.output {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.output>div {
  width: 100%;
  max-width: 600px;
}
</style>